package com.kaily.imagelib;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.Window;

import java.util.concurrent.Executors;

/**
 * 合成图片
 *
 * @date 2018/10/19 下午2:11
 * @author: kaily_zhou
 */
public class MergeImage {
    private MergeImageTask mergeImageTask;

    public void startMerge(Activity activity, MergeCallBack mergeCallBack) {
        mergeImageTask = new MergeImageTask(activity, mergeCallBack);
        mergeImageTask.executeOnExecutor(Executors.newCachedThreadPool());
    }

    public void cancelMerge() {
        try {
            if (mergeImageTask != null && mergeImageTask.getStatus() != AsyncTask.Status.FINISHED) {
                mergeImageTask.cancel(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public interface MergeCallBack {
        Bitmap mergeProcess();

        void callback(Bitmap bitmap);
    }

    public class MergeImageTask extends AsyncTask<String, Void, Bitmap> {
        private Activity activity;
        private ProgressDialog progressdialog;
        private MergeCallBack mergeCallBack;

        public MergeImageTask(Activity activity, MergeCallBack mergeCallBack) {
            this.activity = activity;
            this.mergeCallBack = mergeCallBack;
            createProgressDialog();
        }

        private void createProgressDialog() {
            if (this.activity == null) {
                return;
            }
            progressdialog = new ProgressDialog(this.activity);
            progressdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            progressdialog.setCanceledOnTouchOutside(false);
            progressdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressdialog.setMessage("正在处理，请稍后");
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (progressdialog != null && !progressdialog.isShowing()) {
                progressdialog.show();
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (progressdialog != null && progressdialog.isShowing()) {
                progressdialog.dismiss();
            }

            if (mergeCallBack != null) {
                mergeCallBack.callback(bitmap);
            }

        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            try {
                if (mergeCallBack != null) {
                    return mergeCallBack.mergeProcess();
                }
            } catch (Exception e) {
                return null;
            }
            return null;
        }
    }
}
